package com.ftwj.service;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Slf4j
@Service
public class CaptchaService {

    @Autowired
    private DefaultKaptcha captchaProducer;

    private static final long CAPTCHA_EXPIRATION_TIME = 300000; // 5分钟过期时间，单位：毫秒

    // 生成验证码

    public String generateCaptcha(HttpSession session) {
        String captchaText = captchaProducer.createText();

        // 存储验证码到会话并记录生成时间
        session.setAttribute("CAPTCHA_TEXT", captchaText);
        session.setAttribute("CAPTCHA_GEN_TIME", System.currentTimeMillis());

        log.info("Generated captcha text: {}", captchaText);  // 不在生产环境下记录
        return captchaText;
    }

    // 验证用户输入的验证码
    public boolean validateCaptcha(HttpSession session, String captchaInput) {
        String captchaText = (String) session.getAttribute("CAPTCHA_TEXT");
        Long captchaGenTime = (Long) session.getAttribute("CAPTCHA_GEN_TIME");

        log.debug("Captcha from session: {}", captchaText);
        log.debug("User input captcha: {}", captchaInput);

        // 检查验证码是否存在
        if (captchaText == null || captchaGenTime == null) {
            log.warn("Captcha not found in session or session expired.");
            return false;
        }

        // 检查验证码是否过期
        long currentTime = System.currentTimeMillis();
        if (currentTime - captchaGenTime > CAPTCHA_EXPIRATION_TIME) {
            log.warn("Captcha expired.");
            session.removeAttribute("CAPTCHA_TEXT");
            session.removeAttribute("CAPTCHA_GEN_TIME");
            return false;
        }

        // 验证并清除验证码
        session.removeAttribute("CAPTCHA_TEXT");
        session.removeAttribute("CAPTCHA_GEN_TIME");
        return captchaText.equalsIgnoreCase(captchaInput);
    }
}
